const express = require('express');
const Article = require('../model/Article')
const router = express.Router()

router.post('/article', async (req, res) => {
    const newArticle = await new Article(req.body).save()
    console.log(newArticle);
    if (!newArticle) {
        res.send({
            status: 400,
            msg: '增加文章失败！'
        })
    }
    res.send({
        status: 201,
        msg: '增加文章成功！'
    })
})

router.get('/getarticle', async (req, res) => {
    const articlelist = await Article.find()
    console.log(articlelist);
    if (!articlelist){
        res.send({
            msg:'获取文章列表失败！',
            status: 400,
        })
    }
    res.send({
        msg:'获取文章列表成功！',
        status: 200,
        articlelist
    })
})
router.get('/tagSearch', async (req, res) => {
    //username: req.param("username")
    const articleTaglist = await Article.find({article_tag: req.param("articleTag")})
    console.log(articleTaglist);
    if (!articleTaglist){
        res.send({
            msg:'获取文章列表失败！',
            status: 400,
        })
    }
    res.send({
        msg:'获取文章列表成功！',
        status: 200,
        articleTaglist
    })
})
router.get('/titleSearch', async (req, res) => {
    //username: req.param("username")
    const articleTitlelist = await Article.find({article_title: req.param("articleTitle")})
    console.log(articleTitlelist);
    if (!articleTitlelist){
        res.send({
            msg:'获取文章列表失败！',
            status: 400,
        })
    }
    res.send({
        msg:'获取文章列表成功！',
        status: 200,
        articleTitlelist
    })
})

router.put('/changeThumbs',async (req, res) => {
    const oneArticle = await Article.findOne({_id: req.body._id})
    if (!oneArticle) {
        res.send({
            msg:'点赞失败！',
            status: 400,
        })
    }
    const isThumbs = oneArticle.thumbUserList.indexOf(req.body.username)
    console.log(isThumbs);
    if (isThumbs != -1){
        res.send({
            msg:'不能重复点赞哦！',
            status: 400,
        })
        return
    }
    oneArticle.thumbUserList.push(req.body.username)
    const addThumbUserList = await Article.update({_id: req.body._id},{$set:{thumbUserList: oneArticle.thumbUserList}})
    res.send({
        status: 200
    })
    const article = await Article.update({_id: req.body._id},{$set:{article_thumbs: parseInt(oneArticle.article_thumbs) + 1 }})
})

router.put('/changePreview',async (req, res) => {
    const oneArticle = await Article.findOne({_id: req.body._id})
    if (!oneArticle) {
        res.send({
            msg:'预览失败！',
            status: 400,
        })
    }
    const article = await Article.update({_id: req.body._id},{$set:{article_preview: parseInt(oneArticle.article_preview) + 1 }})
})

module.exports = router
